package com.joycessh.web.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.joycessh.bean.User;
import com.joycessh.dao.UserDao;
import com.joycessh.dao.impl.UserDaoImpl;
import com.joycessh.service.UserService;
import com.joycessh.service.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 * 管理员登录的servlet
 */

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
	    User user = new User();
	    user.setUsername(username);
	    user.setPassword(password);
	    HttpSession session = request.getSession();
	    
	    UserDao userDao = new UserDaoImpl();
	    String forward = "";
	    
	    try {
			if (userDao.check(user)) {
				
					forward = "master.jsp";
					session.setAttribute("name", username);;
				} else {
					forward = "error.jsp";
				}
				
			RequestDispatcher rd = request.getRequestDispatcher(forward);
			rd.forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
